Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

157
Vistas
"SyntaxError: function statement requires a name" when trying to create onClick event in an element in a template literal

When I run the code below I see different behavior in the sandbox I'm using. When I click the button I get "Uncaught SyntaxError: function statement requires a name" in the console but here it is rendering the click event out as text in the button (not sure why?)

Question is—is there a way to pass functions like this to elements created in template literals that are added to the DOM using innerHTML?

const clickHandler = () => {
  console.log("Hi");
};
const root = document.getElementById("root");
root.innerHTML = `<button onClick=${clickHandler}>Click</button>`;
<!DOCTYPE html>
<html>

<body>
    <div id="root"></div>
</body>

</html>

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Inline handlers, being attributes, are essentially strings. When you do

<button onClick=${clickHandler}>

the function gets turned into a string, which results in:

<button onclick="()" ==""> {
  console.log("Hi");
}&gt;Click</button>

which isn't what you want - the automatic fixing of the syntax caused by the interpolation doesn't work well.

When you do it properly, the string in the attribute, when evaluated as JavaScript, may only reference global variables (for all the cases worth mentioning). While you can get your code to work by using the name of the function, and by making sure the function is global:

const clickHandler = () => {
  console.log("Hi");
};
const root = document.getElementById("root");
root.innerHTML = `<button onClick=clickHandler()>Click</button>`;
<div id="root"></div>

A much better approach would be to attach the event listener with JavaScript, instead of an eval-like attribute with scope problems. Insert the elements, then navigate to the element you want the listener attached to, and use addEventListener.

const clickHandler = () => {
  console.log("Hi");
};
const root = document.getElementById("root");
root.innerHTML = `<button>Click</button>`;
root.querySelector('button').addEventListener('click', clickHandler);
<div id="root"></div>

Or use a framework designed for this sort of thing.

const App = () => {
    const clickHandler = () => {
      console.log("Hi");
    };
    return <button onClick={clickHandler}>Click</button>;
};

ReactDOM.createRoot(document.querySelector('.root')).render(<App />);
<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
<div class='root'></div>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda